package com.fau.wmbj.server.controller;


import com.fau.wmbj.server.audit.Audit;
import com.fau.wmbj.server.entity.SysConfig;
import com.fau.wmbj.server.service.SysConfigService;
import com.fau.wmbj.server.storage.StorageConfig;
import com.fau.wmbj.server.storage.StorageConfigService;
import com.fau.wmbj.server.utils.Message;
import com.fau.wmbj.server.utils.Order;
import com.fau.wmbj.server.utils.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 系统配置
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2023-03-21 21:18
 */
@RestController
@RequestMapping("/sys-config")
public class ConfigController {

    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private StorageConfigService storageConfigService;

    /**
     * 获取配置
     */
    @PostMapping(value = "/getAllConfig", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Message getAllConfig() {
        List<SysConfig> sysConfigList = sysConfigService.findAll();
        return Message.success(sysConfigList);
    }

    /**
     * 获取配置
     */
    @PostMapping(value = "/getConfig", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Message getConfig() {
        return Message.success(sysConfigService.getConfigByGroup("sys"));
    }

    /**
     * 修改配置
     */
    @Audit(action = "修改系统配置")
    @PostMapping(value = "/updateConfig", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Message updateRechargeConfig(@RequestBody Map<String, Object> params) {
        for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
            Object value = stringObjectEntry.getValue();
            sysConfigService.updateConfig("sys", stringObjectEntry.getKey(), stringObjectEntry.getValue().toString());
        }
        return Message.success();
    }


    /**
     * 获取存储配置
     */
    @PostMapping(value = "/storage-config-list", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Message storageConfigList(@RequestBody Pageable pageable) {
        pageable.setOrderProperty("order");
        pageable.setOrderDirection(Order.Direction.desc);
        return Message.success(storageConfigService.findPage(pageable));
    }

    /**
     * 更新存储配置
     */
    @PostMapping(value = "/save-storage-config", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Message saveStorageConfig(@RequestBody StorageConfig storageConfig) {
        Long id = storageConfig.getId();
        StorageConfig storageConfig1 = storageConfigService.find(id);
        Map<String, String> attributes = storageConfig.getAttributes();
        storageConfig1.setAttributes(attributes);
        storageConfig1.setIsEnabled(storageConfig.getIsEnabled());
        storageConfigService.update(storageConfig1);
        return Message.success();
    }
}
